package com.aiyige.base.api;

import android.util.Pair;

import com.aiyige.base.api.service.ApiService;

import java.util.HashMap;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by xiachao on 2017/8/10.
 */

public class ApiManager {
    private static Map<Integer, Pair<Retrofit, ApiService>> map = new HashMap<>();
    public static int DEFAULT_TIMEOUT_S = 20;

    public static ApiService getService(int timeoutS) {
        Pair<Retrofit, ApiService> pair = map.get(timeoutS);
        if (pair == null) {
            OkHttpClient client = OkHttpUtil.createOkHttpClient(timeoutS);
            if (client == null) return null;
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(ApiUrls.BaseUrl)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            ApiService service = retrofit.create(ApiService.class);
            pair = new Pair<>(retrofit, service);
            map.put(timeoutS, pair);
        }
        return pair.second;
    }

    public static ApiService getService() {
        return getService(DEFAULT_TIMEOUT_S);
    }

    public static final Callback<ResponseBody> NOOP_CALLBACK = new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {

        }
    };
}
